package com.hmall.gateway.filters;

import cn.hutool.core.text.AntPathMatcher;
import com.hmall.common.exception.UnauthorizedException;
import com.hmall.gateway.config.AuthProperties;
import com.hmall.gateway.utils.JwtTool;
import lombok.RequiredArgsConstructor;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;
@Component
@RequiredArgsConstructor
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    private final AuthProperties authProperties;
    private final JwtTool jwtTool;
    private final AntPathMatcher antPathMatcher = new AntPathMatcher();


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1.获取请求头
        ServerHttpRequest request = exchange.getRequest();
        // 2.判断登录是否需要拦截
        RequestPath path = request.getPath();
        if (isExclude(path.toString())){// 是排除外的
            return  chain.filter(exchange);
        }
        // 3.获取token
        HttpHeaders headers = request.getHeaders();
        List<String> authorization = headers.get("authorization");
        String token = null;
        if (authorization != null && !authorization.isEmpty()){
            token = authorization.get(0);// 因为头部只有一个这样的
        }
        // 4.检验并解析token
        Long userID = null;
        try {// 避免是排除路径外，进来了，但是没有进行登陆的
            userID = jwtTool.parseToken(token);
        }catch (UnauthorizedException e){
            // 拦截，返回401权限不允许
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        // 5.传递用户信息
        String userInfo = userID.toString();
        // 放进请求头
        ServerWebExchange build = exchange.mutate().request(builder -> builder.header("user-info", userInfo))
                .build();
        // 6.
        return chain.filter(build);
    }

    private boolean isExclude(String path) {
        for (String p : authProperties.getExcludePaths()){
            if (antPathMatcher.match(p,path)){
                return true;
            }
        }
        return false;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
